package xyz.lne.researchgroupmanage.controller;


import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import xyz.lne.researchgroupmanage.annotation.AnonymousGetMapping;
import xyz.lne.researchgroupmanage.annotation.AnonymousPostMapping;
import xyz.lne.researchgroupmanage.controller.request.CommitTaskRequest;
import xyz.lne.researchgroupmanage.controller.request.TaskRequest;
import xyz.lne.researchgroupmanage.controller.response.TaskDetailResponse;
import xyz.lne.researchgroupmanage.controller.response.UserCommitTaskResponse;
import xyz.lne.researchgroupmanage.security.UserPower;
import xyz.lne.researchgroupmanage.service.FileService;
import xyz.lne.researchgroupmanage.service.SysUserService;
import xyz.lne.researchgroupmanage.service.TaskService;
import xyz.lne.researchgroupmanage.service.dataTransferObject.TaskDTO;
import xyz.lne.researchgroupmanage.service.dataTransferObject.TaskDetailDTO;
import xyz.lne.researchgroupmanage.service.dataTransferObject.TaskSimpleDTO;
import xyz.lne.researchgroupmanage.service.dataTransferObject.UserCommitTaskDTO;
import xyz.lne.researchgroupmanage.util.SecurityUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author team7
 * @since 2021-01-19
 */
@RestController
@RequestMapping("/task")
public class TaskController {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    FileService fileService;

    @Autowired
    TaskService taskService;

    /**
     * 发布任务
     *
     * @param taskRequest
     * @return
     */
    @AnonymousPostMapping("/releaseTask")
    TaskDetailResponse releaseTask(@RequestBody TaskRequest taskRequest){
        taskRequest.setReleaseUserId(SecurityUtils.getCurrentUserId());
        sysUserService.isLegal(taskRequest.getReleaseUserId());
        taskRequest.getParticipatedUserIdList().forEach(t->sysUserService.isLegal(t));


        return convertToDetailResponse(taskService.releaseTask(convertRequestToDTO(taskRequest),
                taskRequest.getParticipatedUserIdList()));
    }

    /**
     * 完成者提交任务
     * @param commitTaskRequest
     * @return
     */
    @AnonymousPostMapping("/commitTask")
    UserCommitTaskResponse commitTask(@RequestBody CommitTaskRequest commitTaskRequest){
        commitTaskRequest.setCommitUserId(SecurityUtils.getCurrentUserId());
        sysUserService.isLegal(commitTaskRequest.getCommitUserId());
        taskService.isLegal(commitTaskRequest.getTaskId());

        UserCommitTaskDTO dto=taskService.commitTask(convertRequestToDTO(commitTaskRequest));
        return convertCommitDTOToResponse(dto);
    }

    /**
     * 用户确认加入/拒绝某项任务
     * @param commitTaskRequest
     * @return
     */
    @AnonymousPostMapping("/confirmTaskStatus")
    UserCommitTaskResponse confirmTaskStatus (@RequestBody CommitTaskRequest commitTaskRequest){
        commitTaskRequest.setCommitUserId(SecurityUtils.getCurrentUserId());
        sysUserService.isLegal(commitTaskRequest.getCommitUserId());
        taskService.isLegal(commitTaskRequest.getTaskId());

        UserCommitTaskDTO dto=taskService.confirmTaskStatus(convertRequestToDTO(commitTaskRequest));
        return convertCommitDTOToResponse(dto);
    }

    /**
     * 查看当前用户当前任务的状态
     * @param taskId
     * @return
     */
    @AnonymousGetMapping("/getTaskStatus")
    Integer getUserTaskStatus(Integer taskId){

        taskService.isLegal(taskId);
        Integer userId=SecurityUtils.getCurrentUserId();

        if(taskService.isAdminInTask(taskId,userId)){
            return 3;
        }
        else{
            return taskService.getUserTaskStatus(userId,taskId);
        }
    }

    /**
     * 查看当前用户发布的任务列表
     * @return
     */
    
    @AnonymousGetMapping("/getReleasedTaskList")
    List<TaskSimpleDTO> getReleasedTaskListByUserId(){
        return taskService.getReleasedTaskListByUserId(SecurityUtils.getCurrentUserId());
    }

    /**
     * 查看当前用户待完成+未确认的任务列表
     * @return
     */
    @AnonymousGetMapping("/getParticipatedTaskList")
    List<TaskSimpleDTO> getParticipatedTaskListByUserId(){
        return taskService.getParticipatedTaskListByUserId(SecurityUtils.getCurrentUserId());
    }

    /**
     * 查看当前课题的所有任务
     * @param researchId
     * @return
     */
    @AnonymousGetMapping("/getAllTasksByResearchId")
    List<TaskSimpleDTO> getAllTasksByResearchId(Integer researchId){
        return taskService.getAllTasksByResearchId(researchId);
    }

    /**
     * 查看任务细节，利用token获取当前用户id，若当前用户id为该任务发布者，
     * 则自动展示全部信息，否则将仅展示本用户提交信息。
     * @param taskId
     * @return
     */
    @AnonymousGetMapping("/getTaskDetail")
    TaskDetailResponse getTaskDetail(Integer taskId){
        taskService.isLegal(taskId);

        Integer userId=SecurityUtils.getCurrentUserId();

        if(taskService.isAdminInTask(taskId,userId)){
            return convertToDetailResponse(taskService.getTaskAdminDetailByTaskId(taskId));
        }
        else{
            return convertToDetailResponse(taskService.getTaskUserDetailByTaskId(taskId,userId));
        }
    }

        @AnonymousGetMapping("/getMyTaskListInResearch")
    List<TaskSimpleDTO> getUserTaskListInResearch(Integer researchId){
        return taskService.getUserTaskListInResearch(SecurityUtils.getCurrentUserId(),researchId);
    }


    private UserCommitTaskResponse convertCommitDTOToResponse(UserCommitTaskDTO dto) {

        UserCommitTaskResponse response=new UserCommitTaskResponse();

        response.setCommitUserId(dto.getCommitUserId());
        response.setCommitUserName(sysUserService.findNameById(dto.getCommitUserId()));
        response.setTaskId(dto.getTaskId());
        response.setCommitContent(dto.getCommitContent());
        response.setCommitTime(dto.getCommitTime());
        response.setRemark(dto.getRemark());
        response.setStatus(dto.getStatus());
        response.setFileDTO(fileService.findFileByFileId(dto.getCommitFileId()));

        return response;
    }

    private TaskDetailResponse convertToDetailResponse(TaskDetailDTO taskDetailDTO){

        TaskDetailResponse response=new TaskDetailResponse();

        response.setTaskId(taskDetailDTO.getTaskId());
        response.setTaskName(taskDetailDTO.getTaskName());
        response.setReleaseUserId(taskDetailDTO.getReleaseUserId());
        response.setReleaseUserName(taskDetailDTO.getReleaseUserName());
        response.setTaskIntroduction(taskDetailDTO.getTaskIntroduction());
        response.setResearchId(taskDetailDTO.getResearchId());
        response.setResearchName(taskDetailDTO.getResearchName());
        response.setCreateTime(taskDetailDTO.getCreateTime());
        response.setAccomplishedUsersNum(taskDetailDTO.getAccomplishedUsersNum());
        response.setParticipatedUsersNum(taskDetailDTO.getParticipatedUsersNum());

        List<UserCommitTaskDTO> list=taskDetailDTO.getUserCommitTaskDTOList();
        response.setUserCommitTaskResponseList(list==null?null:list.stream()
                        .map(this::convertCommitDTOToResponse).collect(Collectors.toList()));

        return response;
    }

    private TaskDTO convertRequestToDTO(TaskRequest request){

        TaskDTO dto=new TaskDTO();

        dto.setTaskName(request.getTaskName());
        dto.setReleaseUserId(request.getReleaseUserId());
        dto.setTaskIntroduction(request.getTaskIntroduction());
        dto.setResearchId(request.getResearchId());
        dto.setCreateTime(new Date());

        return dto;
    }

    private UserCommitTaskDTO convertRequestToDTO(CommitTaskRequest request){

        UserCommitTaskDTO dto=new UserCommitTaskDTO();
        dto.setTaskId(request.getTaskId());
        dto.setCommitUserId(request.getCommitUserId());
        dto.setCommitContent(request.getCommitContent());
        dto.setCommitFileId(request.getCommitFileId());
        dto.setCommitTime(new Date());
        dto.setRemark(request.getRemark());
        dto.setStatus(request.getStatus());

        return dto;
    }

}

